import { Injectable } from '@angular/core';
import { Methods, WindowMessenger, connect } from 'penpal';
import { DriveEnginService } from './drive-engin.service';

@Injectable({
  providedIn: 'root'
})
export class OpenApiService {

  constructor(private deSvc:DriveEnginService) { 
    this.methods = {
      ...this.methods,
      getOperations (fileName: string,isDir: boolean) { 
        return deSvc.getOperations(fileName,isDir);
      },
      execute (driverId:number,operationId:number, path:string,type:string,source?:any) { 
        return deSvc.execute(driverId,operationId, path,type,source);
      },
      GetDriverList (driverId?:number) {  
        if(driverId){ 
          return deSvc.driveEngine.drivers.value.filter(item=>item.id == driverId);
        } else{
          return deSvc.driveEngine.drivers.value;
        }
      }
    }
 }

//  ## 接口定义 
private methods:Methods = {
  // 信息 
  info(){
    return "desktop";
  }, 
};

//  ## 链接
 link = (iframe: HTMLIFrameElement)=>{
 
  if(iframe.contentWindow == null){
    return null;
  }

  const messenger = new WindowMessenger({
    remoteWindow: iframe.contentWindow!,  
    allowedOrigins: [new URL(iframe.src).origin], 
  });
  
  const connection = connect({
    messenger,
    methods: this.methods,
    // timeout:3000
  });
  
  return connection;
 
 }

}
